package com.gtlab1207.br_security.common;

import com.gtlab1207.br_security.models.dao.CertDao;
import com.gtlab1207.br_security.services.DeleteCertService;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

public class CertUtil {

    private static String baseCertPath = "/Users/shier/Documents/cert/rsa/";;
    /**
     * 校验p12证书的util包
     * @return
     */
    public static String CheckP12(String alias, String password, String certpath){
        String KEYSTORE_FILE = certpath;        //用户p12证书  用户上传的p12证书
        String KEYSTORE_PASSWORD = password;    // 用户密码
        String KEYSTORE_ALIAS = alias;          // 用户别名

        try {
            KeyStore ks = KeyStore.getInstance("PKCS12");

            FileInputStream fis = new FileInputStream(KEYSTORE_FILE);
            // 设置为null 以防密码为空（密码为空会出错）
            char[] nPassword = null;

            if ((KEYSTORE_PASSWORD == null) || KEYSTORE_PASSWORD.trim().equals("")) {
                nPassword = null;
            }else {
                nPassword = KEYSTORE_PASSWORD.toCharArray();
            }

            ks.load(fis, nPassword);

            fis.close();

            // 获取p12证书信息 对证书的拥有者做一个校验
            Enumeration enum1 = ks.aliases();
            String keyAlias = null;
            if (enum1.hasMoreElements()){// we are read in just one certificate.
                keyAlias = (String)enum1.nextElement();
                if( !keyAlias.equalsIgnoreCase(KEYSTORE_ALIAS) ){
                    System.out.println("keyAlias:" + keyAlias);
                    System.out.println("KEYSTORE_ALIAS:" + KEYSTORE_ALIAS);
                    return "alias error";
                }
            }

            // 通过cert做证书有效期的验证
            X509Certificate cert = (X509Certificate) ks.getCertificate(keyAlias);
            Date begin = cert.getNotBefore();
            Date deadline = cert.getNotAfter();
            if(deadline.compareTo(begin) <= 0){
                System.out.println("证书过了有效期");
                // 这里顺势做一个证书删除操作
                DeleteCertService deleteCertService = new DeleteCertService();
                deleteCertService.DeleteCert(alias, baseCertPath + alias);
                return "validity error";
            }

            System.out.println("cert = " + cert);

            // 这里需要做一个CA的校验 表明此证书 是ca颁发的
            String IssuerDN = String.valueOf(cert.getIssuerDN());
            if ( !IssuerDN.equals("O=nanjing, ST=man, EMAILADDRESS=2213352201@qq.com, T=salesman, C=client, UID=管理员, CN=DingJian, L=8, SURNAME=拾贰")){
                return "Issuer error";
            }

            // 获取需要返回的字符串 role 和 organization
            String Subject = String.valueOf(cert.getSubjectDN());
            Map<String, String> Sub = StringUtil.getMap(Subject);
            String o = Sub.get("O");
            String role = Sub.get(" UID");
            String result = "userRole=" + role + ",department=" + o;

            return result;
        } catch (Exception e) {
            System.out.println("验证失败");
            e.printStackTrace();
            return "check error";
        }
    }
}
